package se.webbzon.boltzmann.minigame.effect;

import se.webbzon.boltzmann.minigame.sandbox.DefaultSandBoxItem;
import se.webbzon.boltzmann.minigame.sandbox.SandBox;
import se.webbzon.boltzmann.minigame.sandbox.SandBoxObject;
import se.webbzon.boltzmann.resource.Resources;
import se.webbzon.oschi01.resourceset.ResourceSet;
import se.webbzon.oschi01.textureset.Texture3D;
import se.webbzon.oschi01.worldarea.WorldArea;
import se.webbzon.oschi01.worldcamera.WorldCameraPane;
import se.webbzon.oschi01.worldobject.WorldObject;

public class SandBoxBubble extends DefaultSandBoxItem {
	
	// The 2-dimensional depth of the bubble
	private static final int depth = 3;
	
	// The texture of the bubble
	private final ResourceSet<Texture3D> texture = Resources.getTextureSet("effect_bubble");
	
	// The sand box of this bubble
	private SandBox box;
	
	// The duration and remaining time of the bubble
	private int duration, remaining;
			
	// The speed of the bubble
	private double speed;
	
	/*============================================================
	Constructors
	============================================================*/
	
	public SandBoxBubble() {
		setInstance(new Instance());
		setDraggable(true);
		setDroppable(true);
		remaining = duration = 45 + (int) (90 * Math.random());
		speed = - 1.5 * Math.random();
	}
	
	/*============================================================
	Private Classes
	============================================================*/
	
	private final class Instance extends SandBoxObject {

		public Instance() {
			super(WorldObject.onStep + WorldObject.onPostDraw, depth);
		}

		@Override public void onAttach(SandBox box) {
			SandBoxBubble.this.box = box;
		}

		@Override public void onDetach(SandBox box) {
			SandBoxBubble.this.box = null;
		}

		@Override public void onStep(WorldArea world) {
			final double t = 1 - (remaining / (double) duration);
			setPosition(getX() + Math.cos(4*Math.PI*t),getY() + speed);
			if (remaining > 0)
				remaining--;
			else if (box != null)
				box.removeItem(SandBoxBubble.this);
		}

		@Override public void onPostDraw(WorldArea world, WorldCameraPane hud) {
			int x = (int) getX();
			int y = (int) getY();
			hud.drawTexture(texture.get(0), x-8, y-8, 16, 16);
		}
		
	}

}
